//
//  RefreshView.swift
//  自定义刷新控件
//
//  Created by YYY on 2017/10/30.
//  Copyright © 2017年 成品家（北京）网络科技有限公司. All rights reserved.
//

import UIKit
// MARK: 刷新UI控件布局
class RefreshView: UIView {

    var refershState: PullUpState = .Normal
    {
        didSet
        {
            switch refershState
            {
            case .Normal:
                //普通状态
                tipLabel.text = "下拉刷新数据"
                tipImageView.isHidden = false
                indicatorView.stopAnimating()
                tipImageView.transform = CGAffineTransform.identity
            case .Pulling:
                //下拉状态
                tipLabel.text = "释放刷新数据"
                tipImageView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi-0.001))
            case .Refreshing:
                //刷新状态
                tipLabel.text = "正在刷新数据"
                tipImageView.isHidden = true
                indicatorView.startAnimating()
            }
        }
    }

    // 小人儿图片
    lazy var humanImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
    //提示图片
    lazy var tipImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //提示标签
    lazy var tipLabel = UILabel(text: "下拉开始刷新", fontSize: 14, color: UIColor.darkGray)
    
    //加载标志
    lazy var indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    init() {
        super.init(frame: CGRect())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension RefreshView
{
    func setupUI()
    {
        backgroundColor = UIColor.cyan
        frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64)
        //小人儿
        addSubview(humanImageView)
        //提示图片
        addSubview(tipImageView)
        //提示标签
        addSubview(tipLabel)
        //加载标志
        addSubview(indicatorView)
        humanImageView.center.x = self.center.x
        
        let top = humanImageView.height - self.height
        
        humanImageView.setTop(newTop: -top)
        
        let rect = (tipLabel.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 20), options: [.usesLineFragmentOrigin], attributes: [NSAttributedStringKey.font: tipLabel.font], context: nil)
        
        let left = (UIScreen.main.bounds.width - tipImageView.bounds.width - rect.width)/2.0
        tipImageView.setLeft(newLeft: left)
        tipImageView.center.y = self.center.y
        
        tipLabel.frame = CGRect(origin: CGPoint(x: tipImageView.right, y: 0), size: rect.size)
        tipLabel.center.y = tipImageView.center.y

        //指示器
        indicatorView.center = tipImageView.center
        indicatorView.stopAnimating()
        indicatorView.hidesWhenStopped = true
    }
}
